const express = require('express');
const cors = require('cors');
const Crawler = require('./crawlerModule');

const app = express();
app.use(cors());
app.use(express.json());
const config = require('./config/index.js');
// 创建爬虫实例
const crawler = new Crawler();

// 更新接口
app.post('/api/crawl', async (req, res) => {
  try {
    const { type } = req.body;
    const urls = config[type].urls;
    const selector = config[type].selector;
    const outputFile = config[type].outputFile;
    // 验证必要参数
    if (!type) {
      return res.status(400).json({
        success: false,
        message: '请提供有效type参数'
      });
    }
    // 执行爬虫
    const result = await crawler.crawl(
      urls,
      selector,
      outputFile || 'crawled_data.json'
    );

    res.json(result);

  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});

app.post('/api/crawlData', async (req, res) => {
  try {
    const { name } = req.body;
    // 验证必要参数
    if (!name) {
      return res.status(400).json({
        success: false,
        message: '请提供有效name参数'
      });
    }

    // 读取赛车数据.json文件
    const carDataPath = './datas/赛车数据.json';
    const carData = require(carDataPath);

    // 查找对应的数据
    const targetData = carData.find(item => item.title.includes(name));
    if (!targetData) {
      return res.status(404).json({
        success: false,
        message: '未找到对应的数据'
      });
    }

    // 执行爬虫
    const result = await crawler.crawlSingle(
      targetData.link,  // 使用找到的link
      {
        dates: '#pageDetail',
        img: 'img'
      }
    );
    const obj = result?.result?.data;
    const dates = obj?.dates[0]?.text;

    // 提取特性分析到赛车数据一览之间的内容
    let content = dates || '';
    let startStr = '';
    let endStr = '';
    let startIndex = ''
    let endIndex = ''
    if (targetData.url.includes('17943')) { // 赛车
      startStr = '特性分析';
      endStr = '赛车数据一览';
      startIndex = content.indexOf(startStr);
      endIndex = content.indexOf(endStr);

    } else if (targetData.url.includes('17944')) { // 宠物
      startStr = '属性';
      endStr = '获取方式';
      startIndex = content.indexOf(startStr);
      endIndex = content.indexOf(endStr);
    }
    let extractedContent = '';
    if (startIndex !== -1 && endIndex !== -1 && startIndex < endIndex) {
      extractedContent = content.substring(startIndex + startStr.length, endIndex).trim();
    }

    const img = obj?.img[5]?.attributes?.src;
    const responseData = {
      title: targetData.title,
      link: targetData.link,
      img,
      extractedContent
    };

    res.json(responseData);
  } catch (error) {
    res.status(500).json({
      success: false,
      message: error.message
    });
  }
});
const PORT = process.env.PORT || 5100;
const HOST = '0.0.0.0';
app.listen(PORT, HOST, () => {
  console.log(`服务器运行在 http://localhost:${PORT}`);
});